package com.pangolin.pangolinim.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class MySocket {
    private Socket mSocket;
    private InputStream mInputStream;
    private OutputStream mOutputStream;

    public boolean connect(String host , int port)  throws IOException {
        //mSocket = new Socket(CHAT_SERVER, CHAT_PORT);
        mSocket = new Socket();
        SocketAddress socAddress = new InetSocketAddress(host, port);
        mSocket.connect(socAddress, 3000);  //设置链接超时
        //mSocket.setSoTimeout(10000);                 //设置IO超时
        mSocket.setKeepAlive(true);
        mOutputStream = mSocket.getOutputStream();
        mInputStream = mSocket.getInputStream();
        return mSocket.isConnected();
    }

    public boolean isconnect() {
        return mSocket == null ? false : mSocket.isConnected();
    }

    public void disconnect() throws IOException{
        if(mInputStream != null){
            mSocket.shutdownInput();
            mInputStream.close();
            mInputStream = null;
        }
        if(mOutputStream != null){
            mSocket.shutdownOutput();
            mOutputStream.close();
            mOutputStream = null;
        }
        if(mSocket != null){
            mSocket.close();
            mSocket = null;
        }
    }

    public void send(byte []data , int len) throws IOException{
        if (mSocket.isConnected())
            mOutputStream.write(data , 0 , len);
    }

    public byte[] recv(int len) throws IOException{
        if (mSocket.isConnected()) {
            byte data[] = new byte[len];
            mInputStream.read(data , 0 , len);
            return data;
        }else{
            return null;
        }
    }
}
